package com.shortlink.utils;

import org.apache.commons.codec.binary.Base64;
import org.apache.shardingsphere.encrypt.strategy.spi.Encryptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Properties;

public class AesEncryptor implements Encryptor {

    private static final Logger log = LoggerFactory.getLogger(AesEncryptor.class);
    private static final String KEY = "kl9o56u98gvjhw9i"; // 请替换为您的密钥
    private static final String IV = "grjei564389tj843"; // 请替换为您的IV
    private Properties properties = new Properties();

    @Override
    public void init() {
        // 初始化操作，如果需要的话
    }

    @Override
    public String encrypt(Object plaintext) {
        try {
            String data = plaintext.toString();
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keyspec = new SecretKeySpec(KEY.getBytes("UTF-8"), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(IV.getBytes("UTF-8"));
            cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
            byte[] encrypted = cipher.doFinal(data.getBytes("UTF-8"));
            return Base64.encodeBase64String(encrypted);
        } catch (Exception e) {
            log.error("AES encrypt error", e);
            return null;
        }
    }

    @Override
    public Object decrypt(String ciphertext) {
        try {
            byte[] encryptedData = Base64.decodeBase64(ciphertext);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keyspec = new SecretKeySpec(KEY.getBytes("UTF-8"), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(IV.getBytes("UTF-8"));
            cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
            byte[] original = cipher.doFinal(encryptedData);
            return new String(original, "UTF-8");
        } catch (Exception e) {
            log.error("AES decrypt error", e);
            return null;
        }
    }

    @Override
    public String getType() {
        return "AES";
    }

    @Override
    public Properties getProperties() {
        return properties;
    }

    @Override
    public void setProperties(Properties properties) {
        this.properties = properties;
    }
}